//2022年1月31日16:55:25
import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import config from '@/config/index.js'
import {
	ElMessage as Message
} from 'element-plus'

function qs(data) {
	if (isEmpty(data)) return ""
	if (typeof data !== 'object') return data;
	let arr = []

	for (let k in data) {
		if (!isEmpty(data[k])) {
			if (typeof data[k] === 'string') {
				arr.push(encodeURIComponent(k.toString().trim()) + "=" + encodeURIComponent(data[k].trim()))
			} else {
				arr.push(encodeURIComponent(k.toString().trim()) + "=" + encodeURIComponent(JSON.stringify(data[k])))
			}
		}
	}
	return arr.join("&")
}

function isEmpty(v) {
	if (v === null || v === undefined) return true
	if (typeof v === 'string' && v.trim() === '') return true
	return false;
}
/**
 * BASE_URL从配置文件中加载
 */
export const BASE_URL = config.URL

/**
 * 发送请求前启动NProgress
 */
function BaseRequestInterceptor(config) {
	NProgress.start()
	return config
}

/**
 * 收到请求后停止NProgress
 */
function BaseSuccessResponseInterceptor(config) {
	NProgress.done()
	return config.data
}

const instance = axios.create({
	baseURL: BASE_URL,
	withCredentials: true,
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
	},
	timeout: 5000
})

// 请求拦截
instance.interceptors.request.use(BaseRequestInterceptor)

export const $get = function(url, params) {
	let queryString = qs(params)
	if (queryString === '') {
		return new Promise((resolve, reject) => {
			instance.request({
				method: 'get',
				url: url
			}).then(res => {
				resolve(BaseSuccessResponseInterceptor(res))
			}).catch(e => {
				NProgress.done()
				Message.error("请求失败")
				reject(e)
			})
		})
	} else {
		return new Promise((resolve, reject) => {
			instance.request({
				method: 'get',
				url: url + "?" + queryString
			}).then(res => {
				resolve(BaseSuccessResponseInterceptor(res))
			}).catch(e => {
				NProgress.done()
				Message.error("请求失败")
				reject(e)
			})
		})
	}
}


export const $post = function(url, data, cb) {
	return new Promise((resolve, reject) => {
		instance.request({
			method: 'post',
			data: qs(data),
			url: url,
			onUploadProgress: cb
		}).then(res => {
			resolve(BaseSuccessResponseInterceptor(res))
		}).catch(e => {
			NProgress.done()
			Message.error("请求失败")
			reject(e)
		})
	})
}


export const $POST = function(url, data, cb) {
	let fd = new FormData()
	for (let key in data) {
		if (!isEmpty(data[key])) {
			fd.append(key, data[key])
		}
	}
	return new Promise((resolve, reject) => {
		instance.request({
			method: 'post',
			data: fd,
			url: url,
			onUploadProgress: cb,
			timeout: 0
		}).then(res => {
			resolve(BaseSuccessResponseInterceptor(res))
		}).catch(e => {
			NProgress.done()
			Message.error("请求失败")
			reject(e)
		})
	})
}

export const $download = function(url, data, cb) {
	let fd = new FormData()
	for (let key in data) {
		if (!isEmpty(data[key])) {
			fd.append(key, data[key])
		}
	}
	return new Promise((resolve, reject) => {
		instance.request({
				url,
				method: 'post',
				responseType: 'blob',
				data: fd,
				onUploadProgress: cb,
				timeout: 0
			})
			.then(response => {
				let res = {}
				if (response.headers.remakes) {
					// java的URLEncoder和decodeURIComponent有坑,空格会被编码成+,解码时应该把+号变成%20(空格)
					let json = decodeURIComponent(response.headers.remakes.replace(/\+/g, '%20'))
					let data = JSON.parse(json)
					Object.assign(res, data)
				}
				res.binary = response.data
				NProgress.done()
				resolve(res)
			})
			.catch(e => {
				NProgress.done()
				Message.error("请求失败")
				reject(e)
			})
	})
}

export const download = function(url, params, cb) {
	return new Promise((resolve, reject) => {
		let queryString = qs(params)
		instance.request({
				url: url + "?" + queryString,
				method: 'get',
				responseType: 'blob',
				onUploadProgress: cb,
				timeout: 0
			})
			.then(response => {
				let res = {}
				if (response.headers.remakes) {
					// java的URLEncoder和decodeURIComponent有坑,空格会被编码成+,解码时应该把+号变成%20(空格)
					let json = decodeURIComponent(response.headers.remakes.replace(/\+/g, '%20'))
					let data = JSON.parse(json)
					Object.assign(res, data)
				}
				res.binary = response.data
				NProgress.done()
				resolve(res)
			})
			.catch(e => {
				NProgress.done()
				Message.error("请求失败")
				reject(e)
			})
	})
}

export const get = $get
export const post = $post
export const POST = $POST
